<template>
  <el-tabs
    type="border-card"
    style="margin: 0 20px; height: 93vh"
    @tab-click="tabChange"
    v-model="$store.state.activeName4"
  >
    <el-tab-pane label="累计位移" name="累计位移">
      <el-form inline :model="form">
        <el-form-item label="开始时间">
          <el-date-picker
            type="datetime"
            placeholder="选择开始时间"
            size="mini"
            v-model="form.startTime"
            default-time="00:00:00"
            :picker-options="startTimePicker"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
            type="datetime"
            placeholder="选择结束时间"
            size="mini"
            v-model="form.endTime"
            default-time="00:00:00"
            :picker-options="endTimePicker"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="info" size="mini" @click="query">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="info" size="mini" @click="week">一周</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="info" size="mini" @click="month">一月</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="info" size="mini" @click="all">全部</el-button>
        </el-form-item>
      </el-form>
      <div id="offset" class="chart"></div>
      <el-card shadow="hover" v-if="table.lineTitle">
        <div slot="header">
          <span>{{ table.lineTitle }}(&nbsp;{{ table.lineTime }}&nbsp;)</span>
        </div>
        <table>
          <tr>
            <th width="80">高度(m)</th>
            <th width="90">位移(mm)</th>
            <th width="100">变化(mm/天)</th>
          </tr>
          <tr v-for="(item, index) in table.tableData" :key="index">
            <td>{{ item[1] }}</td>
            <td>{{ item[0] }}</td>
            <td v-if="table.ytData">
              {{ (item[0] - table.ytData[index][0]).toFixed(1) }}
            </td>
            <td v-if="!table.ytData">-</td>
          </tr>
        </table>
      </el-card>
    </el-tab-pane>
    <el-tab-pane label="变化曲线" name="变化曲线">
      <el-form inline :model="form2">
        <el-form-item label="开始时间">
          <el-date-picker
            type="datetime"
            placeholder="选择开始时间"
            size="mini"
            v-model="form2.startTime"
            default-time="00:00:00"
            :picker-options="startTimePicker2"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
            type="datetime"
            placeholder="选择结束时间"
            size="mini"
            v-model="form2.endTime"
            default-time="00:00:00"
            :picker-options="endTimePicker2"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="info" size="mini" @click="query2">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="info" size="mini" @click="week2">一周</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="info" size="mini" @click="month2">一月</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="info" size="mini" @click="all2">全部</el-button>
        </el-form-item>
      </el-form>
      <div id="curve" class="chart"></div>
    </el-tab-pane>
  </el-tabs>
</template>

<script>
import Axios from "axios";
import moment from "moment";
import * as serviceApi from "../../../../common/service.config";
Axios.defaults.withcredentials = true;

export default {
  inject: ["reload"],
  name: "DeepChart",
  props: {
    node: Object,
  },
  data() {
    return {
      form: {
        startTime: null,
        endTime: moment().format("YYYY-MM-DD 00:00:00"),
      },
      form2: {
        startTime: null,
        endTime: moment().format("YYYY-MM-DD 00:00:00"),
      },
      table: {
        lineTitle: null,
        lineTime: null,
        tableData: null,
        ytData: null,
      },
      totalOffsetChart: null,
      rockHistoryChart: null,
    };
  },
  computed: {
    startTimePicker() {
      return {
        disabledDate: (time) =>
          this.form.startTime
            ? time.getTime() > new Date(this.form.endTime).getTime()
            : false,
      };
    },
    endTimePicker() {
      return {
        disabledDate: (time) =>
          this.form.endTime
            ? time.getTime() > new Date().getTime() ||
              time.getTime() < new Date(this.form.startTime).getTime()
            : false,
      };
    },
    startTimePicker2() {
      return {
        disabledDate: (time) =>
          this.form2.startTime
            ? time.getTime() > new Date(this.form2.endTime).getTime()
            : false,
      };
    },
    endTimePicker2() {
      return {
        disabledDate: (time) =>
          this.form2.endTime
            ? time.getTime() > new Date().getTime() ||
              time.getTime() < new Date(this.form2.startTime).getTime()
            : false,
      };
    },
  },
  methods: {
    tabChange(tab) {
      this.$store.dispatch("getTabName4", tab.paneName);
    },
    createTotalOffsetChart(sensorNumber, lineTitle, xdata) {
      let sensorNumberList = [];
      sensorNumberList.push(lineTitle);
      let queryData = {
        sensorNumber: "",
      };
      queryData.sensorNumber = sensorNumber;
      let XData = xdata;
      let splitArea = XData;
      function getDays(day1, day2) {
        // 获取入参字符串形式日期的Date型日期
        String.prototype.getDate = function () {
          var strArr = this.split("-");
          return new Date(strArr[0], strArr[1] - 1, strArr[2]);
        };
        // 给月和天，不足两位的前面补0
        function fz(num) {
          if (num < 10) {
            num = "0" + num;
          }
          return num;
        }
        Date.prototype.getYMD = function () {
          // 将结果放在数组中，使用数组的join方法返回连接起来的字符串，并给不足两位的天和月十位上补零
          return [
            this.getFullYear(),
            fz(this.getMonth() + 1),
            fz(this.getDate()),
          ].join("-");
        };

        var st = day1.getDate();
        var et = day2.getDate();
        var retArr = [];
        // 获取开始日期的年，月，日
        var yyyy = st.getFullYear(),
          mm = st.getMonth(),
          dd = st.getDate();
        // 循环
        while (st.getTime() != et.getTime()) {
          retArr.push(st.getYMD());
          // 使用dd++进行天数的自增
          st = new Date(yyyy, mm, ++dd);
        }
        // 将结束日期的天放进数组
        retArr.push(et.getYMD());
        return retArr;
      }
      let option = {
        baseOption: {
          timeline: {
            axisType: "category",
            autoPlay: true,
            playInterval: 1000,
            controlStyle: {
              position: "right",
            },
            left: 20,
            right: 20,
            data: (() => {
              return getDays(
                moment(this.form.startTime).format("YYYY-MM-DD"),
                moment(this.form.endTime).format("YYYY-MM-DD")
              );
            })(),
            label: {
              formatter: function (s) {
                return s;
              },
            },
          },
          title: {
            text: "深部位移站点累计位移量#" + this.node.label,
            left: "center",
          },
          legend: {
            show: true,
            top: "7%",
            data: (function () {
              let dataArr = [];
              let length = sensorNumberList.length;
              for (let i = 0; i < length; i++) {
                dataArr.push(sensorNumberList[i]);
              }
              return dataArr;
            })(),
            textStyle: {
              color: "black",
              fontSize: 14,
            },
          },
          calculable: true,
          grid: (function () {
            let length = sensorNumberList.length;
            let gridArray = [];
            let width = 100 / length;
            for (let i = 0; i < length; i++) {
              let grid = {
                left: "30%",
                top: "20%",
                width: "40%",
                height: "60%",
              };
              gridArray.push(grid);
            }
            return gridArray;
          })(),
          tooltip: {
            trigger: "axis",
            axisPointer: {
              type: "line",
            },
            formatter: function (params) {
              if (params[0]) {
                if (params[0].data.length > -1) {
                  return (
                    "高度: " +
                    params[0].data[1] +
                    "m<br>位移: " +
                    params[0].data[0] +
                    "mm"
                  );
                } else {
                  return "高度:  m<br>位移:  mm";
                }
              }
            },
          },
          xAxis: (function () {
            let length = sensorNumberList.length;
            let xAxisArray = [];
            for (let i = 0; i < length; i++) {
              let xAxis;
              xAxis = {
                gridIndex: 0,
                min: -1.1 * splitArea,
                max: 1.1 * splitArea,
                name: "位移(mm)",
                interval: splitArea / 20,
                nameGap: 30,
                nameLocation: "middle",
                axisLabel: {
                  show: true,
                  rotate: -70,
                  formatter: function (value, index) {
                    for (let i = 0; i < splitArea * 1.1; i++) {
                      if (value % (splitArea / 10) !== 0) {
                        return "  ";
                      }
                    }
                    return value;
                  },
                },
                splitLine: {
                  show: false,
                  boundaryGap: false,
                  color: "blue",
                  type: "value",
                },
                splitArea: {
                  show: true,
                  areaStyle: {
                    opacity: 0.45,
                    color: [
                      "#FE1C23",
                      "#FE1C23",
                      "#FE9C28",
                      "#FE9C28",
                      "#FE9C28",
                      "#FE9C28",
                      "#FE9C28",
                      "#66cc66",
                      "#66cc66",
                      "#66cc66",
                      "#66cc66",
                      "#66cc66",
                      "#66cc66",
                      "#66cc66",
                      "#66cc66",
                      "#66cc66",
                      "#66cc66",
                      "#66cc66",
                      "#66cc66",
                      "#66cc66",
                      "#66cc66",
                      "#66cc66",
                      "#66cc66",
                      "#66cc66",
                      "#66cc66",
                      "#66cc66",
                      "#66cc66",
                      "#66cc66",
                      "#66cc66",
                      "#66cc66",
                      "#66cc66",
                      "#66cc66",
                      "#66cc66",
                      "#66cc66",
                      "#66cc66",
                      "#66cc66",
                      "#66cc66",
                      "#FE9C28",
                      "#FE9C28",
                      "#FE9C28",
                      "#FE9C28",
                      "#FE9C28",
                      "#FE1C23",
                      "#FE1C23",
                    ],
                  },
                }, //保留网格区域
              };
              xAxisArray.push(xAxis);
            }
            return xAxisArray;
          })(),
          yAxis: (function () {
            let length = sensorNumberList.length;
            let yAxisArray = [];
            for (let i = 0; i < length; i++) {
              let yAxis = {
                name: "高度(m)",
                //position: 'left',
                gridIndex: i,
                // min: 'dataMin',
                max: 0,
                type: "value",
                scale: true,
                nameLocation: "end",
                nameGap: 10,
              };
              yAxisArray.push(yAxis);
            }
            return yAxisArray;
          })(),
        },
        options: [],
      };
      return option;
    },
    pushDataToChart(dayList, option, lineTitle) {
      let ytData = null;
      for (let i = 0; i < dayList.length; i++) {
        let dataOption = { series: [] };
        let sensorList = dayList[i].list;
        let m = 0;
        for (let j = 0; j < sensorList.length; j++) {
          if (
            sensorList[j] == null ||
            sensorList[j] == "" ||
            sensorList[j] == undefined
          ) {
            continue;
          }
          let tunnelList = sensorList[j].list;
          if (
            tunnelList == null ||
            tunnelList == "" ||
            tunnelList == undefined
          ) {
            continue;
          }
          m = j + 1;
          dataOption.series.push({
            name: lineTitle,
            type: "line" /*line*/,
            symbolSize: 10,
            lineStyle: {
              normal: {
                width: 2,
              },
              smooth: true,
            },
            smooth: true,
            xAxisIndex: j,
            yAxisIndex: j,
            data: (function () {
              let data = [],
                y;
              for (let k = 0; k < tunnelList.length; k++) {
                data.push([
                  parseFloat(tunnelList[k].offset).toFixed(1),
                  parseFloat(tunnelList[k].height).toFixed(2),
                ]);
                y = tunnelList[k].height;
              }
              return data;
            })(),
            itemStyle: {
              normal: {
                color: "#397B8B",
              },
              lineStyle: "pic",
              smooth: true,
            },
          });
        }
        option.options.push(dataOption);
      }
      this.totalOffsetChart.clear();
      this.totalOffsetChart.setOption(option);
      this.totalOffsetChart.resize();
      this.totalOffsetChart.on("timelinechanged", (params) => {
        if (option.options[params.currentIndex]) {
          let result = option.options[params.currentIndex].series[0].data;
          let lineTime = option.baseOption.timeline.data[params.currentIndex];
          let showTable = (ytData, data, lineTime, lineTitle) => {
            this.table.lineTitle = lineTitle;
            this.table.lineTime = lineTime;
            this.table.tableData = data;
            this.table.ytData = ytData;
          };
          showTable(ytData, result, lineTime, lineTitle);
          ytData = result;
        }
      });
    },
    search(startTime, endTime) {
      let queryData = {
        startTime,
        endTime,
      };
      sessionStorage.setItem("startTime", queryData.startTime);
      sessionStorage.setItem("endTime", queryData.endTime);
      this.reload();
    },
    query() {
      this.search(
        moment(this.form.startTime).format("YYYY-MM-DD"),
        moment(this.form.endTime).format("YYYY-MM-DD")
      );
    },
    week() {
      this.search(
        moment().subtract(7, "d").format("YYYY-MM-DD"),
        moment().format("YYYY-MM-DD")
      );
    },
    month() {
      this.search(
        moment().subtract(31, "d").format("YYYY-MM-DD"),
        moment().format("YYYY-MM-DD")
      );
    },
    all() {
      this.search(
        moment().subtract(1860, "d").format("YYYY-MM-DD"),
        moment().format("YYYY-MM-DD")
      );
    },
    createRockHistoryEchart(resultObj, requestTotalOffset) {
      if (resultObj.parameter.list != null && resultObj.parameter.list != "") {
        if (resultObj.parameter.list.length != "0") {
          let theDateData = [];
          let length = resultObj.parameter.list.length;
          for (let j = 0; j < length; j++) {
            theDateData.push(resultObj.parameter.list[j].theDate);
          }
          let chartOption = {
            title: {
              text:
                this.node.label +
                "站点" +
                requestTotalOffset.startTime +
                "至" +
                requestTotalOffset.endTime +
                "变化曲线",
              left: "center",
            },
            tooltip: {
              trigger: "axis",
            },
            legend: {
              top: 30,
              data: (function () {
                let legendData = [];
                let tempData = resultObj.parameter.list[0].list[0];
                let tunnelCount = tempData.list.length;
                for (let i = 1; i < tunnelCount; i++) {
                  let legend =
                    tempData.list[i].tunnelNumber +
                    "通道(深度" +
                    tempData.list[i].height +
                    "m)";
                  legendData.push(legend);
                }
                return legendData;
              })(),
            },
            grid: {
              left: "3%",
              right: "4%",
              bottom: "3%",
              containLabel: true,
            },
            toolbox: {
              feature: {
                saveAsImage: {},
              },
              right: "5%",
            },
            xAxis: {
              name: "时间",
              type: "category",
              boundaryGap: false,
              data: theDateData,
            },
            yAxis: {
              name: "位移(mm)",
              type: "value",
            },
            color: [
              "#027602",
              "#0101F6",
              "#840284",
              "#FF0000",
              "#27727B",
              "#FE8463",
              "#9BCA63",
              "#FAD860",
              "#F3A43B",
              "#60C0DD",
              "#D7504B",
              "#C6E579",
              "#F4E001",
              "#F0805A",
              "#26C0C0",
            ],
            series: (function () {
              let seriesData = [];
              let length = resultObj.parameter.list.length;
              let tempData = resultObj.parameter.list[0].list[0];
              let tunnelCount = tempData.list.length;
              for (let i = 1; i < tunnelCount; i++) {
                let legend =
                  tempData.list[i].tunnelNumber +
                  "通道(深度" +
                  tempData.list[i].height +
                  "m)";
                let ydata = [];
                for (let j = 0; j < length; j++) {
                  let obj = resultObj.parameter.list[j].list[0];
                  ydata.push(obj.list[i].offset);
                }
                let series = {
                  name: legend,
                  type: "line",
                  smooth: true,
                  lineStyle: {
                    normal: {
                      width: 3,
                    },
                  },
                  data: ydata,
                };
                seriesData.push(series);
              }
              return seriesData;
            })(),
          };
          this.rockHistoryChart.setOption(chartOption);
          this.rockHistoryChart.resize();
        }
      }
    },
    search2(startTime, endTime) {
      let queryData = {
        startTime,
        endTime,
      };
      sessionStorage.setItem("startTime", queryData.startTime);
      sessionStorage.setItem("endTime", queryData.endTime);
      this.reload();
    },
    query2() {
      this.search2(
        moment(this.form2.startTime).format("YYYY-MM-DD"),
        moment(this.form2.endTime).format("YYYY-MM-DD")
      );
    },
    week2() {
      this.search2(
        moment().subtract(7, "d").format("YYYY-MM-DD"),
        moment().format("YYYY-MM-DD")
      );
    },
    month2() {
      this.search2(
        moment().subtract(31, "d").format("YYYY-MM-DD"),
        moment().format("YYYY-MM-DD")
      );
    },
    all2() {
      this.search2(
        moment().subtract(1860, "d").format("YYYY-MM-DD"),
        moment().format("YYYY-MM-DD")
      );
    },
  },
  mounted() {
    this.totalOffsetChart = this.$echarts.init(
      document.getElementById("offset")
    );
    this.rockHistoryChart = this.$echarts.init(
      document.getElementById("curve")
    );
    let updateTotalOffsetChart = (sensorNumberList, lineTitle) => {
      this.totalOffsetChart.showLoading();
      let queryData = {
        startTime: moment().subtract(1860, "d").format("YYYY-MM-DD"),
        endTime: moment().format("YYYY-MM-DD"),
      };
      if (sessionStorage.getItem("startTime"))
        queryData.startTime = sessionStorage.getItem("startTime");
      if (sessionStorage.getItem("endTime"))
        queryData.endTime = sessionStorage.getItem("endTime");
      this.form.startTime = moment(queryData.startTime).format(
        "YYYY-MM-DD 00:00:00"
      );
      this.form.endTime = moment(queryData.endTime).format(
        "YYYY-MM-DD 00:00:00"
      );
      Axios({
        url: serviceApi.KB_API,
        method: "post",
        data: `appMsg={"parameter":"{\\"sensorNumberList\\":\\"${this.node.sensorNumber}\\",\\"tunnelNumber\\":\\"\\",\\"endTime\\":\\"${queryData.endTime}\\",\\"startTime\\":\\"${queryData.startTime}\\"}","serviceCode":"queryTotalOffset","timestamp":"","uuid":""}`,
      }).then((res) => {
        let dayList = res.data.parameter.list;
        Axios({
          url: serviceApi.KB_API,
          method: "post",
          data: `appMsg={"parameter":"{\\"sensorNumber\\":\\"${this.node.sensorNumber}\\"}","serviceCode":"offsetChartX","timestamp":"","uuid":""}`,
        }).then((res) => {
          let XData = res.data.parameter.warningValueSetDmo.xdata;
          this.totalOffsetChart.hideLoading();
          this.pushDataToChart(
            dayList,
            this.createTotalOffsetChart(sensorNumberList, lineTitle, XData),
            lineTitle
          );
        });
      });
    };
    let updateRockHistoryEchart = () => {
      this.rockHistoryChart.showLoading();
      let queryData = {
        startTime: moment().subtract(1860, "d").format("YYYY-MM-DD"),
        endTime: moment().format("YYYY-MM-DD"),
      };
      if (sessionStorage.getItem("startTime"))
        queryData.startTime = sessionStorage.getItem("startTime");
      if (sessionStorage.getItem("endTime"))
        queryData.endTime = sessionStorage.getItem("endTime");
      this.form2.startTime = moment(queryData.startTime).format(
        "YYYY-MM-DD 00:00:00"
      );
      this.form2.endTime = moment(queryData.endTime).format(
        "YYYY-MM-DD 00:00:00"
      );
      Axios({
        url: serviceApi.KB_API,
        method: "post",
        data: `appMsg={"parameter":"{\\"sensorNumberList\\":\\"${this.node.sensorNumber}\\",\\"tunnelNumber\\":\\"\\",\\"endTime\\":\\"${queryData.endTime}\\",\\"startTime\\":\\"${queryData.startTime}\\"}","serviceCode":"queryTotalOffset","timestamp":"","uuid":""}`,
      }).then((res) => {
        this.rockHistoryChart.hideLoading();
        this.createRockHistoryEchart(res.data, queryData);
      });
    };
    let DataAnalysis = async () => {
      await updateTotalOffsetChart(this.node.sensorNumber, this.node.label);
      await updateRockHistoryEchart();
    };
    DataAnalysis();
  },
};
</script>

<style lang="less" scoped>
.chart {
  width: 1600px;
  height: 75vh;
}
.el-tab-pane {
  position: relative;
  .el-card {
    position: absolute;
    top: 30%;
    right: 5%;
    text-align: center;
    table {
      font-size: 15px;
    }
  }
}
</style>